<!--
 * @Author: linyongxin linyongxin@ellipspace.com
 * @Date: 2023-08-03 10:56:54
 * @LastEditors: linyongxin linyongxin@ellipspace.com
 * @LastEditTime: 2024-12-25 15:31:54
 * @FilePath: \geoserver-web-utils\src\components\Color\color-mapping-dialog.vue
 * @Description: 配色数值映射表
-->
<template>
    <el-dialog
        v-model="dialogVisible"
        title="配色数值映射表"
        class="color-mapping-dialog"
        width="580px"
        :close-on-click-modal="false"
        :before-close="closeDialog"
        draggable
    >
        <div class="color-mapping-continer">
            <el-table
                ref="tableRef"
                stripe
                show-overflow
                :data="colorMapTableData"
                :column-config="{ resizable: true }"
                :row-config="{ keyField: 'id', isHover: true }"
                :max-height="'580px'"
                :checkbox-config="{ checkRowKeys: defaultSelecteRowKeys, highlight: true }"
                :sort-config="{ sortMethod: handleSortMethod }"
            >
                <el-table-column type="selection" width="60" />
                <el-table-column prop="color" label="颜色" width="60">
                    <template #default="{ row }">
                        <!-- <div class="fieldColor-div" @click="selectColor(row)">
                            <span
                                class="fieldColor-span cursor-pointer"
                                :class="{ slash: ['#ffffff00'].includes(row.color) }"
                                :style="{ 'background-color': row.color }"
                            />
                        </div> -->
                        <el-color-picker v-model="row.color" show-alpha />
                    </template>
                </el-table-column>
                <el-table-column prop="borderColor" label="边框" width="60">
                    <template #default="{ row }">
                        <el-color-picker v-model="row.borderColor" show-alpha />
                    </template>
                </el-table-column>
                <el-table-column v-if="layerType == 'raster'" prop="quantity" label="值">
                    <template #default="{ row }">
                        <el-input v-model="row.quantity" type="text" @blur="handleBlur" />
                    </template>
                </el-table-column>
                <el-table-column v-if="layerType == 'vector'" prop="value" label="值">
                    <template #default="{ row }">
                        <el-input v-model="row.value" type="text" @blur="handleBlur" />
                    </template>
                </el-table-column>
                <el-table-column prop="label" label="图例标注">
                    <template #default="{ row }">
                        <el-input v-model="row.label" type="text" />
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <span>
                    <el-button @click="resettingTable"> 重置 </el-button>
                    <el-button @click="insertEvent()"> + </el-button>
                    <el-button @click="removeSelectRowEvent"> - </el-button>
                    <el-button @click="cancleAll"> 删除全部 </el-button>
                </span>
                <span class="right-button">
                    <el-button class="ml-auto mr-2 cancel-black" @click="closeDialog"> 取消 </el-button>
                    <el-button class="ml-auto mr-2" type="primary" @click="saveEvent"> 确定 </el-button>
                </span>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, computed, nextTick, toRef } from 'vue'
import { ElTable } from 'element-plus'
import type { ColorMap, ColorMapEntry, ColorMapType } from 'geostyler-style'
import { type colorStripType, type IColorMapEntryExtend } from '@/interface/color'
import { rgbaStringToHex } from '@/utils/color'

interface emitInterface {
    (e: 'update:visible', v: boolean): void
    (e: 'updateRasterColorMap', v: ColorMap): void
    (e: 'updateVectorColorMap', v: IColorMapEntryExtend[]): void
}

const emit = defineEmits<emitInterface>()
// const xTable = ref<VxeTableInstance<RowVO>>()
interface propsType {
    layerType: 'vector' | 'raster'
    visible: boolean
    colorMapEntrys: IColorMapEntryExtend[]
    colorRenderType?: ColorMapType
    colorStrip: colorStripType
}
const props = withDefaults(defineProps<propsType>(), {
    layerType: 'raster',
    visible: false,
    colorRenderType: 'ramp',
    colorMapEntrys: () => {
        return []
    },
    colorStrip: () => {
        return {
            startColor: '#000',
            endColor: '#FDD693',
            name: 'Magma',
            value: 'Magma',
            label: 'Magma',
            count: 5,
            step: 5,
            colorOpt: ['#000', '#160E3B', '#942C80', '#EC5960', '#FDD693'],
            colorStrip: true,
            gradient: true,
        }
    },
})
const dialogVisible = toRef(props, 'visible')
const defaultColorStrip = toRef(props, 'colorStrip')
const currentColorRenderType = toRef(props, 'colorRenderType')
const defaultSelecteRowKeys = ref<any>([])
const tableRef = ref<InstanceType<typeof ElTable>>()
const colorMapTableData = ref<IColorMapEntryExtend[]>([])
const orignColorMapTableData = toRef(props, 'colorMapEntrys')
colorMapTableData.value = JSON.parse(JSON.stringify(orignColorMapTableData.value))
/**
 * @description: 重置
 */
const resettingTable = () => {
    colorMapTableData.value = []
    nextTick(() => {
        colorMapTableData.value = JSON.parse(JSON.stringify(orignColorMapTableData.value))
    })
}
/**
 * @description: 关闭当前弹窗
 * @return {*}
 */
const closeDialog = () => {
    // stylePresetForm = reactive<Styles.ResStyleInfo>(JSON.parse(JSON.stringify(defaultPresetForm)))
    emit('update:visible', false)
    // dialogVisible.value = false
}
// 增加
const insertEvent = () => {
    let newColor = '#ff0000'
    if (
        defaultColorStrip.value &&
        (defaultColorStrip.value.colorOpt as string[]).length > colorMapTableData.value.length
    ) {
        newColor = (defaultColorStrip.value.colorOpt as string[])[colorMapTableData.value.length] as string
    } else {
        newColor = (defaultColorStrip.value.colorOpt as string[])[
            (defaultColorStrip.value.colorOpt as string[]).length - 1
        ] as string
    }
    let newLabel = ''
    let newQuantity = 1

    // <sld:ColorMap type="intervals">
    //           <sld:ColorMapEntry color="#30123b" label="&lt;= 0.3804" quantity="0.38036628"/>
    //           <sld:ColorMapEntry color="#28bceb" label="0.3804 - 0.5258" quantity="0.52578966000000005"/>
    //           <sld:ColorMapEntry color="#a4fc3c" label="0.5258 - 0.6712" quantity="0.67121304000000004"/>
    //           <sld:ColorMapEntry color="#fb7e21" label="0.6712 - 0.8166" quantity="0.81663642000000003"/>
    //           <sld:ColorMapEntry color="#7a0403" label="> 0.8166" quantity="inf"/>
    //         </sld:ColorMap>
    if (currentColorRenderType.value == 'ramp') {
        newLabel = '1'
        newQuantity = 1
    } else if (currentColorRenderType.value == 'intervals') {
        if (colorMapTableData.value.length == 0) {
            newLabel = '&lt;= 1'
            newQuantity = 1
        } else {
            newLabel = '1 - 2'
            newQuantity = 2
        }
    } else if (currentColorRenderType.value == 'values') {
        newLabel = '1'
        newQuantity = 1
    }
    colorMapTableData.value.push({
        color: newColor,
        borderColor: newColor,
        quantity: newQuantity,
        label: newLabel,
        opacity: 1,
    })
}
// 删除
const removeSelectRowEvent = () => {
    const currentSellectRows = tableRef.value?.getSelectionRows()
    colorMapTableData.value = colorMapTableData.value.filter((filterItem:any) => {
        return !currentSellectRows.includes(filterItem)
    })
}
// 删除所有
const cancleAll = () => {
    colorMapTableData.value = []
}
const handleBlur = () => {
    // const $table = xTable.value
    // if ($table) {
    //     $table.sort('name')
    // }
}
const handleSortMethod = (params: any) => {
    const { sortList, data } = params
    const [{ field, order }] = sortList
    const isFdps = true
    if (!isFdps) {
        return data.sort((a: any, b: any) => {
            const aVal = a[field]
            const bVal = b[field]
            return order === 'asc' ? aVal - bVal : bVal - aVal
        })
    }
    return data.sort((a: any, b: any) => {
        const aVal = a[field].split(',')[0].slice(1)
        const bVal = b[field].split(',')[0].slice(1)
        return order === 'asc' ? aVal - bVal : bVal - aVal
    })
}
// 保存
const saveEvent = () => {
    if (props.layerType == 'raster') {
        const formatedColorMap: ColorMap = {
            type: currentColorRenderType.value,
            colorMapEntries: colorMapTableData.value.map(mapItem => {
                let currentColor = ''
                let currentOpacity = 1
                const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
                if (reg.test((mapItem.color as string).toLowerCase())) {
                    currentColor = mapItem.color as string
                    currentOpacity = 1
                } else {
                    currentColor = rgbaStringToHex(mapItem.color as string)?.hexColor as string
                    currentOpacity = rgbaStringToHex(mapItem.color as string)?.alpha as number
                }
                return {
                    color: currentColor,
                    quantity: mapItem.quantity,
                    label: mapItem.label,
                    opacity: currentOpacity,
                } as ColorMapEntry
            }),
        }
        emit('updateRasterColorMap', formatedColorMap)
    } else if (props.layerType == 'vector') {
        emit(
            'updateVectorColorMap',
            colorMapTableData.value.map(mapItem => {
                let currentColor = ''
                let currentOpacity = 1
                let currentBorderColor = ''
                let currentBorderOpacity = 1
                const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
                if (mapItem.color) {
                    if (reg.test((mapItem.color as string).toLowerCase())) {
                        currentColor = mapItem.color as string
                        currentOpacity = 1
                    } else {
                        currentColor = rgbaStringToHex(mapItem.color as string)?.hexColor as string
                        currentOpacity = rgbaStringToHex(mapItem.color as string)?.alpha as number
                    }
                } else {
                    currentColor = '#000000'
                    currentOpacity = 0
                }
                if (mapItem.borderColor) {
                    if (reg.test((mapItem.borderColor as string).toLowerCase())) {
                        currentBorderColor = mapItem.borderColor as string
                        currentBorderOpacity = 1
                    } else {
                        currentBorderColor = rgbaStringToHex(mapItem.borderColor as string)?.hexColor as string
                        currentBorderOpacity = rgbaStringToHex(mapItem.borderColor as string)?.alpha as number
                    }
                } else {
                    currentBorderColor = '#000000'
                    currentBorderOpacity = 0
                }
                return {
                    color: currentColor,
                    borderColor: currentBorderColor,
                    borderopacity: currentBorderOpacity,
                    value: mapItem.value,
                    label: mapItem.label,
                    opacity: currentOpacity,
                } as IColorMapEntryExtend
            }),
        )
    }

    closeDialog()
}
watch(
    () => orignColorMapTableData.value,
    () => {
        colorMapTableData.value = JSON.parse(JSON.stringify(orignColorMapTableData.value))
    },
    {
        immediate: true,
        deep: true,
    },
)
onMounted(() => {
    // colorMapTableData.value = layerFormData.value.colorMapping
})
// () => layerFormData.value.colorMapping,
// val => {
//     colorMapTableData.value = val
// },
</script>

<style scoped lang="scss">
.color-mapping-dialog {
    .color-mapping-continer {
        width: 100%;
        max-height: 770px;
    }
    .dialog-footer {
        display: flex;
        .right-button {
            margin-left: auto;
        }
    }
}
</style>
